/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-08-20 15:18:07
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-08-22 17:16:46
 * @FilePath: /vue3-uniapp/src/service/useRequestSubject.ts
 */

import { Observable, Subject, type Subscription } from 'rxjs';

import { readMyAreaEs, OrderSearchRequestParam } from '@/api/my';

const subjectMaps = new Map<any, Subject<unknown>>();

export const getRequestSubject = <T extends (...rest: any) => Promise<any>>(
    request: T
): Subject<Parameters<T>> => {
    if (!subjectMaps.has(request)) {
        subjectMaps.set(request, new Subject<unknown>());
    }
    return subjectMaps.get(request) as Subject<Parameters<T>>;
};

export const createNotifyRequestChange = <
    T extends (...rest: any) => Promise<any>
>(
    request: T
): ((...state: Parameters<T>) => void) => {
    return (...state: Parameters<T>) => {
        getRequestSubject(request).next(state);
    };
};

export const createUseRequestSubject = <
    T extends (...rest: any) => Promise<any>
>(
    request: T
) => {
    return (fn: (...state: Parameters<T>) => void) => {
        const subscription = getRequestSubject(request)
            .pipe(throttleTime(1000))
            .subscribe((state) => {
                fn(...state);
            });

        onBeforeUnmount(() => {
            subscription.unsubscribe();
        });
    };
};
